package net.ncraft.mc.ezframework.core.gui.esign;

import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.BlockPosition;
import lombok.Getter;
import lombok.Setter;
import net.ncraft.mc.ezframework.core.SpigotEzFrameworkCore;
import net.ncraft.mc.ezframework.core.handler.packages.PackageCenter;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

public class ESign {

    @Getter
    private final String[] lines = new String[4];
    private BlockPosition blockPosition;
    @Setter
    private SignAction onClose;
    private final ESign ESign = this;

    public void open(Player player) {
        PacketContainer packet = new PacketContainer(PacketType.Play.Server.OPEN_SIGN_EDITOR);
        blockPosition = new BlockPosition(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
        packet.getBlockPositionModifier().write(0, blockPosition);

        if (PackageCenter.getProtocolManager() == null) {
            return;
        }
        PackageCenter.getProtocolManager().sendServerPacket(player, packet);
        onClose(lines);
    }
    private String color(String input) {
        return ChatColor.translateAlternateColorCodes('&', input);
    }

    private void onClose(String[] lines) {
        PacketAdapter packetAdapter = new PacketAdapter(SpigotEzFrameworkCore.getPlugin(), PacketType.Play.Client.UPDATE_SIGN) {
            @Override
            public void onPacketReceiving(PacketEvent event) {
                if (!event.getPacket().getBlockPositionModifier().read(0).equals(blockPosition)) {
                    return;
                }
                lines[0] = event.getPacket().getStringArrays().read(0)[0];
                lines[1] = event.getPacket().getStringArrays().read(0)[1];
                lines[2] = event.getPacket().getStringArrays().read(0)[2];
                lines[3] = event.getPacket().getStringArrays().read(0)[3];
                if (onClose != null) {
                    onClose.run(ESign);
                }
                PackageCenter.getProtocolManager().removePacketListener(this);
            }
        };
        PackageCenter.getProtocolManager().addPacketListener(packetAdapter);
    }


}
